import React, { FC, useEffect, useRef, useState } from "react";
import {
  Button,
  Input,
  message,
  Select,
  Drawer,
  Table,
  DatePicker,
  Tag,
  Descriptions,
  Image,
} from "antd";
import { getOriginString, getSecretString } from "@/utils/encrypt";
import { useRequest } from "@umijs/hooks";
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";
import "./index.css";
import { EyeOutlined, RiseOutlined, SearchOutlined } from "@ant-design/icons";
import getImgInfo from "@/utils/getImgInfo";
import exportExcel from "@/utils/exportExcel";

const { Option } = Select;
const { RangePicker } = DatePicker;

const optionList = [
  {
    title: "全部",
    value: "",
  },
  {
    title: "已删除",
    value: "-1",
  },
  {
    title: "已过期",
    value: "0",
  },
  {
    title: "有效",
    value: "1",
  },
];

const infoKey = [
  {
    key: "leaveName",
    title: "请假人姓名",
  },
  {
    key: "leavePhone",
    title: "请假人电话",
    render: (phone: string) => <>{getOriginString(phone)}</>,
  },
  {
    title: "学校名称",
    key: "collegeName",
  },
  {
    key: "studentId",
    title: "学号",
    render: (phone: string) => <>{phone}</>,
  },
  {
    title: "请假时间",
    render: (text: any) => <>{`${text.startTime}~${text.endTime}`}</>,
  },
  {
    title: "创建时间",
    key: "createTime",
  },
  {
    title: "教师姓名",
    key: "teacherName",
  },
  {
    title: "教师电话",
    key: "teacherPhone",
    render: (phone: string) => <>{getOriginString(phone)}</>,
  },
  {
    title: "状态",
    key: "state",
    render: (state: string) => {
      const temState = state || 0;
      const item = list.find((item) => item.key === temState);
      return <Tag color={item?.color}>{item?.text}</Tag>;
    },
  },
  {
    title: "请假事由",
    key: "leaveReason",
    render: (reason: string) => <div className={"reason"}>{reason}</div>,
  },
  {
    title: "附件",
    key: "additionalPhoto",
    render: (photo: string) =>
      photo && (
        <div className={"reason"}>
          <Image
            src={`${url.GET_PERSON_LEAVE_URL}?accessToken=${getImgInfo(photo)}`}
          />
        </div>
      ),
  },
];
const list = [
  { color: "#722ed1", text: "已删除", key: -1 },
  { color: "#108ee9", text: "有效", key: 1 },
  {
    color: "#f50",
    text: "已过期",
    key: 0,
  },
];

let tempParams = {
  leavePhone: "",
  state: "",
  startDate: "",
  endDate: "",
};

const Leaves: FC = () => {
  const columns = [
    {
      title: "请假人姓名",
      key: "leaveName",
      dataIndex: "leaveName",
    },
    {
      title: "请假人电话",
      key: "leavePhone",
      dataIndex: "leavePhone",
      render: (phone: string) => <div>{getOriginString(phone)}</div>,
    },
    {
      title: "学校名称",
      key: "collegeName",
      dataIndex: "collegeName",
    },

    {
      title: "开始时间",
      key: "startTime",
      dataIndex: "startTime",
    },
    {
      title: "结束时间",
      key: "endTime",
      dataIndex: "endTime",
    },
    {
      title: "创建时间",
      key: "createTime",
      dataIndex: "createTime",
    },
    {
      title: "教师姓名",
      key: "teacherName",
      dataIndex: "teacherName",
    },
    {
      title: "教师电话",
      key: "teacherPhone",
      dataIndex: "teacherPhone",
      render: (phone: string) => <div>{getOriginString(phone)}</div>,
    },
    {
      title: "状态",
      key: "state",
      dataIndex: "state",
      render: (state: string) => {
        const temState = state || 0;
        const item = list.find((item) => item.key === temState);
        return <Tag color={item?.color}>{item?.text}</Tag>;
      },
    },
    {
      title: "操作",
      render: (item: any) => (
        <Tag
          color={"#108ee9"}
          icon={<EyeOutlined />}
          className="executed"
          onClick={() => getVisitor({ id: item.id })}
        >
          查看
        </Tag>
      ),
    },
  ];

  const [visible, setVisible] = useState(false);
  const [info, setInfo] = useState({});
  const params = useRef({
    endDate: "",
    startDate: "",
    state: "",
    leavePhone: "",
  });
  const { tableProps, run } = useRequest(
    (current, params) =>
      fetchRequest(url.GET_LEAVES_TABLE, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params,
      }),
    {
      paginated: true,
      manual: true,
      formatResult: (response: any) => {
        return {
          list: response.data?.rows,
          total: response.data?.total,
          success: response.success,
          errorMsg: response.errorMsg,
        };
      },
    }
  );

  const { run: improtRun } = useRequest(
    (params) => fetchRequest(url.EXPORT_LEAVES, params),
    {
      manual: true,
      onSuccess: (response, params) => {
        if (response.success) {
          console.log(response.data);

          const tempKeys = {};
          infoKey.forEach((keyItem) => {
            if (keyItem.key) {
              if (keyItem.title !== "附件") {
                tempKeys[keyItem.key] = keyItem.title;
              }
            }
          });
          const data = response?.data?.map((item: any) => {
            const tempItem = {};
            Object.keys(tempKeys).forEach((keyItem) => {
              console.log(tempKeys[keyItem]);
              tempItem[tempKeys[keyItem]] = item[keyItem];
            });
            tempItem["教师电话"] = getOriginString(item?.teacherPhone);
            tempItem["请假人电话"] = getOriginString(item?.leavePhone);
            tempItem["身份证号"] = getOriginString(item?.idNumber);
            tempItem["状态"] = list.find(
              (listItem) => listItem.key === item?.state
            )?.text;

            return tempItem;
          });

          exportExcel(data, "请假记录.xlsx");
        } else {
          message.error(response.errorMsg);
        }
      },
    }
  );

  const selectClick = async () => {
    params.current = {
      ...tempParams,
    };

    if (tempParams.leavePhone) {
      params.current.leavePhone = getSecretString(tempParams.leavePhone);
    }

    const data = await run({ pageSize: 10, current: 1 }, params.current);

    if (!data.success) {
      message.error(data.errorMsg);
    }
  };
  const stateChange = (value: string) => {
    tempParams.state = value;
  };

  const timerChange = (date: any, dateString: any) => {
    tempParams.startDate = dateString[0];
    tempParams.endDate = dateString[1];
  };

  const getVisitor = async (params: any) => {
    const { data, success } = await fetchRequest(url.GET_LEAVES, params);
    if (success) {
      setInfo(data);
      setVisible(true);
    }
  };

  useEffect(() => {
    (async () => {
      Object.keys(tempParams).map((item) => (tempParams[item] = ""));
      await selectClick();
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const importClick = async () => {
    params.current = {
      ...tempParams,
    };
    if (tempParams.leavePhone) {
      params.current.leavePhone = getSecretString(tempParams.leavePhone);
    }
    await improtRun({ ...params.current });
  };

  /*render*/
  const search = () => (
    <div className={"search"}>
      <div className={"search-item"}>
        <div className={"title"}>请假电话号码:</div>
        <div>
          <Input
            placeholder={"请输入请假电话"}
            onInput={(e) => (tempParams.leavePhone = e.currentTarget.value)}
          />
        </div>
      </div>

      <div className={"search-item"}>
        <div className={"title"}>请选择时间:</div>
        <div>
          <RangePicker onChange={timerChange} />
        </div>
      </div>
      <div className={"search-item"}>
        <div className={"title"}>请选择状态:</div>
        <div>
          <Select defaultValue={optionList[0].title} onChange={stateChange}>
            {optionList.map((item, index) => (
              <Option key={index} value={item.value}>
                {item.title}
              </Option>
            ))}
          </Select>
        </div>
      </div>
      <div className={"btn"}>
        <Button
          type={"primary"}
          onClick={selectClick}
          icon={<SearchOutlined />}
        >
          查询
        </Button>
        <Button type={"primary"} onClick={importClick} icon={<RiseOutlined />}>
          导出
        </Button>
      </div>
    </div>
  );

  const table = () => (
    <>
      <Table
        className={"table-form"}
        columns={columns}
        rowKey="id"
        {...(tableProps as any)}
      />
    </>
  );

  const drawer = () => (
    <>
      <Drawer
        title="请假详情"
        placement="right"
        closable={false}
        onClose={() => setVisible(false)}
        visible={visible}
        width={1200}
      >
        <Descriptions bordered>
          {infoKey.map((item: any, index) => (
            <Descriptions.Item label={item.title} key={index}>
              {item.render
                ? item.render(item.key ? info[item.key] : info)
                : info[item.key]}
            </Descriptions.Item>
          ))}
        </Descriptions>
      </Drawer>
    </>
  );
  return (
    <div className={"wrap bulk"}>
      {search()}
      {table()}
      {drawer()}
    </div>
  );
};

export default Leaves;
